package com.hyt.it.ogt.controller.ykcj.common;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;

import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.it.ogt.ykcj.common.utils.StringUtils;
import com.hyt.it.ogt.ykcj.common.utils.file.FileUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;

/**
 * 通用导出模板文件请求处理
 *
 * @author yaojian
 */
@Api(tags = "common.2.通用导出模板文件", value = "通用导出模板文件")
@ApiSort(value = 2)
//@RestController
public class ExportController {
    private static final Logger log = LoggerFactory.getLogger(ExportController.class);

    /**
     * 导出文件请求
     *
     * @param fileName 文件名称
     */
    @ApiOperation(value = "1.导出template路径下的模板文件 ", notes = "没有对应文件响应为空")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "测试文件.txt", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true)
    })
    @ApiOperationSort(1)
    public void fileDownload(@PathVariable(name = "fileName") String fileName,
                             HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            ClassPathResource classPathResource = new ClassPathResource("template/" + fileName);
            String filePath = classPathResource.getFile().getAbsolutePath();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
